package com.zj.juc.study.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName AtomicBaseTypeDemo
 * @Description 基本类型原子类demo
 * @createTime 2025年01月03日 20:06
 */
public class AtomicBaseTypeDemo {

    public static final Integer SIZE=50;

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(SIZE);
        MyNumberDemo myNumberDemo = new MyNumberDemo();
        for (int i = 0; i < SIZE; i++) {
            new Thread(()->{
                try {
                    for (int j = 0; j < 1000; j++) {
                        myNumberDemo.addPlusPlus();
                    }
                } finally {
                    //countDownLatch一直减
                    countDownLatch.countDown();
                }
            },String.valueOf(i)).start();

        }

        try {
            //卡住main线程直到countDownLatch减为0
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(myNumberDemo.atomicInteger);//main线程此时取得的数量不一定是50000
    }
}

class MyNumberDemo{
    AtomicInteger atomicInteger = new AtomicInteger(0);

    public void addPlusPlus(){
        atomicInteger.getAndIncrement();
    }

}